import re
from fastapi import APIRouter, Form
from application.utils.access_token import redis_access_token
from application.utils.sqlalchemy_session import get_db
from sqlalchemy.orm import Session
from apps.frontapp.model import PrizeResult, WinningGen
from apps.frontapp.tools import *
from application.config.redis import *
from fastapi import Depends
import datetime
import requests
from apps.log_config import setup_logging
from fastapi import BackgroundTasks

frontapp_router = APIRouter()
info_logger, error_logger = setup_logging()


@frontapp_router.post("/openid", summary='获取用户openid和用户信息')
async def get_user_openid(background_tasks: BackgroundTasks, js_code: str = Form(...)):
    data = get_openid(js_code)
    try:
        data = {
            "openid": data['openid']
        }
        return {'status': 1, 'message': '成功', 'data': data}
    except:
        error_logger.error("用户openid获取失败")
        return {'status': 0, 'message': '用户登录失败请重新登录', 'data': None}


@frontapp_router.post("/phone", summary='获取用户手机号')
async def get_user_phone(openid: str = Form(...), code: str = Form(...)):
    access_token = redis_access_token()  # 先获取access_token
    data = get_phone(access_token, code)
    if data['errcode'] == 0:
        return {'status': 1, 'message': '成功', 'data': data}
    else:
        error_logger.error("获取用户手机号失败" + ' openid: ' + openid)
        return {'status': 0, 'message': '获取用户手机号失败', 'data': data}


# 向一汽丰田提交
def go_submit_clue(new_dic):
    try:
        url = 'https://llmp.ftms.com.cn/collection/openapi/clues/postlead'
        headers = {
            'authorization': '03d0160f3b8a5832153e392ed6a7babf0fcde117efc0fe89c9aa7d5cec7b95f5',
            'random': '12345678',
            'timestamp': '1646791495583',
        }
        data = {
            "datas": [new_dic]
        }
        response = requests.post(url=url, json=data, headers=headers)
        info_logger.error("一丰线索提交" + str(new_dic) + str(response.json()))
    except Exception as e:
        error_logger.error("一丰线索提交失败" + str(new_dic) + '原因' + str(e))


@frontapp_router.post("/submit_clue", summary='预约试驾_提交销售线索')
async def submit_clue(background_tasks: BackgroundTasks, openid: str = Form(...), name: str = Form(...),
                      phone: str = Form(...), dealerId: str = Form(...), seriesId: int = Form(...)):
    new_dic = {
        "mediaId": "1004602f5853407f8eb5dfd4f778f553",
        "mediaLeadId": "2024春节抖音红包",
        "mediaLeadType": "2024年春节抖音红包CNY活动-微信朋友圈",
        "channelKeyId": 116,
        "activity": 2707,
        # "name": "杜玛",
        # "phone": "15559195121",
        # "dealerId": "10111",
        # "seriesId": 9,
        "name": name,
        "phone": phone,
        "dealerId": dealerId,
        "seriesId": seriesId,
        'create_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
    }
    # redis_json_set30day(10, openid, new_dic)
    uuid = openid_uuid(openid)
    last_digit = uuid[-1]
    redis_key_map = {
        '0': 7, '1': 7, '2': 7, '3': 7,
        '4': 8, '5': 8, '6': 8, '7': 8,
        '8': 9, '9': 9, 'A': 9, 'B': 9,
        'C': 10, 'D': 10, 'E': 10, 'F': 10
    }
    redis_json_permanent(redis_key_map.get(last_digit), openid, new_dic)
    background_tasks.add_task(go_submit_clue, new_dic)
    return {'status': 1, 'message': '成功', 'data': new_dic}


@frontapp_router.post("/draw_prize", summary='开始抽奖[手机和卡券]')
async def draw_prize(background_tasks: BackgroundTasks, openid: str = Form(...), secret_key: str = Form(...),
                     request_time: str = Form(...), phone: str = Form(...), mm_str: str = Form(...),
                     dealerCode: str = Form(...), db: Session = Depends(get_db)):
    # 加密通道---------------------------------------------------------------------------------
    md5_str = md5_encrypt(openid + request_time + jm_list[int(mm_str)])
    if md5_str != secret_key:
        error_logger.error("加密不合法的请求" + ' openid: ' + openid)
        return JSONResponse(content={'status': 0, 'message': '不合法的请求', 'data': None}, status_code=405)
    if not bool(re.match(r'^1[3-9]\d{9}$', phone)):
        return JSONResponse(content={'status': 0, 'message': '手机号格式有误', 'data': None}, status_code=405)
    # 正式开始请求-------------------------------------------------------
    # an_dic = redis_json_get(2, openid)
    an_dic = get_redis(openid)
    if an_dic:
        return {'status': 0, 'message': '您已经参加过抽奖', 'data': None}
    prize = redis_json_get(4, 'prize_phone')
    probability = float(prize['prize_probability'])  # 中奖概率
    data_dic = {
        'openid': openid,
        'phone': phone,
        'state': 0,
        'prize_name': '卡券',
        'dealerCode': dealerCode,
        'check_code': go_check_code(openid, phone),
        'create_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'vx_card': []
    }
    zj = lottery_draw(probability)  # 进行抽奖
    if zj:
        if prize['residue_sum'] <= 0:  # 库存剩余小于等于0
            yf_code_list = for_add_card(phone, dealerCode)
            data_dic['vx_card'] = yf_code_list if yf_code_list else None
            # redis_json_set30day(2, openid, data_dic)
            save_redis(openid, data_dic)
            return {'status': 0, 'message': '很遗憾没有中奖', 'data': data_dic}
        current_draw_prize = redis_get(11, 'current_draw_prize')
        if current_draw_prize:
            yf_code_list = for_add_card(phone, dealerCode)
            data_dic['vx_card'] = yf_code_list if yf_code_list else None
            # redis_json_set30day(2, openid, data_dic)
            save_redis(openid, data_dic)
            return {'status': 0, 'message': '很遗憾没有中奖', 'data': data_dic}
        else:
            redis_set(11, 2, 'current_draw_prize', 1)
            prize['residue_sum'] -= 1  # 库存减一
            redis_json_permanent(4, 'prize_phone', prize)  # 刷新奖品
            data_dic['state'] = 1
            data_dic['prize_name'] = prize['prize_name']
            save_redis(openid, data_dic)  # 记录结果
            redis_json_set30day(12, openid, data_dic)  # 单独记中奖
            model_data = PrizeResult(openid=data_dic['openid'], phone=data_dic['phone'],
                                     create_time=data_dic['create_time'],
                                     dealerCode=data_dic['dealerCode'],
                                     vx_card=data_dic['vx_card'],
                                     check_code=data_dic['check_code'],
                                     state=data_dic['state'], prize_name=data_dic['prize_name'])
            db.add(model_data)
            db.commit()
            return {'status': 1, 'message': '恭喜您中奖了', 'data': data_dic}
    else:
        yf_code_list = for_add_card(phone, dealerCode)
        data_dic['vx_card'] = yf_code_list if yf_code_list else None
        # redis_json_set30day(2, openid, data_dic)
        save_redis(openid, data_dic)
        return {'status': 0, 'message': '很遗憾没有中奖', 'data': data_dic}


@frontapp_router.post("/prize_result_current", summary='个人中心_当期期抽奖记录列表')
async def prize_result_current(openid: str = Form(...)):
    an_dic = get_redis(openid)
    if not an_dic:
        return {'status': 3, 'message': '您没有参加此活动', 'data': None}
    if an_dic['state'] == 0:
        return {'status': 2, 'message': '您未中奖', 'data': an_dic}
    if an_dic['state'] == 1:
        return {'status': 1, 'message': '您中奖了', 'data': an_dic}


@frontapp_router.post("/winning_gen", summary='中奖留资')
async def winning_gen(openid: str = Form(...), name: str = Form(...), phone: str = Form(...),
                      address: str = Form(...), check_code: str = Form(...), db: Session = Depends(get_db)):
    try:
        if redis_exists(13, openid):
            return {'status': 0, 'message': '已经提交不能再次提交', 'data': None}
        new_dic = {
            "openid": openid,
            "name": name,
            "phone": phone,
            "address": address,
            "check_code": check_code,
        }
        redis_json_set30day(13, openid, new_dic)
        model_data = WinningGen(openid=new_dic['openid'], name=new_dic['name'], check_code=new_dic['check_code'],
                                phone=new_dic['phone'], address=new_dic['address'])
        db.add(model_data)
        db.commit()
        return {'status': 1, 'message': '成功', 'data': new_dic}
    except:
        return {'status': 0, 'message': '已经提交', 'data': None}


@frontapp_router.post("/winning_gen2", summary='中奖留资_二次进入是否提交')
async def winning_gen2(openid: str = Form(...)):
    if redis_exists(13, openid):
        return {'status': 0, 'message': '已经提交不能再次提交', 'data': None}
    else:
        return {'status': 1, 'message': '还未提交', 'data': None}


@frontapp_router.post("/vx_coupons_create", summary='一丰卡券添加微信卡包')
async def vx_Coupons_create(phone: str = Form(...), dealerCode: str = Form(...)):
    yf_code_list = for_add_card(phone, dealerCode)
    if yf_code_list:
        return {'status': 1, 'message': '成功', 'data': yf_code_list}
    else:
        return {'status': 0, 'message': '签名创建失败', 'data': None}
